package com.test.utils;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;


public class UserRealm extends AuthorizingRealm {


    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();

        //角色的集合
        Set<String> roles = new HashSet<String>();
        roles.add(userName);

        //权限的集合
        Set<String> permissions = new HashSet<String>();

        permissions.add("/index");
        if (userName.equals("admin")) {
            permissions.add("/wx");
            permissions.add("/wx/wxlogin");

        }


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addRoles(roles);//设置角色
        authorizationInfo.addStringPermissions(permissions);//设置权限

        return authorizationInfo;

    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();

//        UserDao userDao = new UserDao();
//        UsersEntity login = userDao.query(userName);
//        System.out.println("sql login="+login);
        if (!userName.equals("admin")) {

            throw new UnknownAccountException();

        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userName, "123456", getName());
        return info;

    }


    @Override
    public String getName() {
        return getClass().getName();
    }

}
